package rickyGame.controller.state
{
	import flash.events.MouseEvent;
	import flash.geom.Point;
	
	import ricky.game.Actor;
	import ricky.game.Actor2D;
	import ricky.quadtree.Leaf;
	import ricky.quadtree.Morton;
	import ricky.scene.Scene;
	import ricky.utils.Utils;
	
	import rickyGame.controller.Controller;
	import rickyGame.game.Building;
	import rickyGame.game.GameState;
	import rickyGame.game.Goods;
	import rickyGame.game.Player;
	import rickyGame.game.action.MoveLeafAction;
	import rickyGame.game.action.MsgAct;
	import rickyGame.game.scene.Pathfinder;
	import rickyGame.net.MsgType;
	import rickyGame.net.WorkQueue;
	import rickyGame.ui.Cursor;
	
	/**
	 * 状态机
	 */
	public class State
	{
		public var state:uint=0;
		public var par:*;
		
		public function State(par:*=null)
		{
			this.par=par;
		}
		
		/**
		 * 状态
		 */
		public function create():void
		{
			Cursor.show(Cursor.NORMAL);
		}
		
		/**
		 * 当前状态下的操作
		 */
		public function operate(par:*):void
		{
			if(par is  Array)
			{
				var path:Array;var c:Controller
				var m:Player=Controller.instance.actor;
				var tarp:Point;
				tarp=par[0];
				
				if(par.length>1)
				{
					var actor:Actor=par[1];
					var l:int=Utils.gridDistance1(m.graphic.x,m.graphic.y,tarp.x,tarp.y);

					if(actor is Goods || actor is Building) //如果点击的时物品和建筑
					{
//						if(l<actor.data.rangeVisible)
//							WorkQueue.instance.pushRecive(MsgType.SERVER_USE_GOODS,m,actor);
//						else
						{
							 path=pathFinder(tarp,m);
							 if(path)
							 {
//								 var msg:MsgAct=new MsgAct(m,MsgType.SERVER_USE_GOODS,m,actor);
								 var mv:MoveLeafAction=new MoveLeafAction(m,null,path);
//								 mv.addNext(msg);
								 m.addAct(mv);
							 }
						}

					}
				}else	if(tarp)
				{
					JDebug.traceObj(tarp,tarp);
					path=pathFinder(tarp,m);
					if(path)
					{
						var mv1:MoveLeafAction;
						mv1=new MoveLeafAction(m,null,path);
						m.addAct(mv1);
					}
//					JDebug.traceObj(path);
//						WorkQueue.instance.pushRecive(MsgType.CLIENT_MOVE_IN_PATH,m,path);

				}
			}
		}
		
		public static function pathFinder(p:Point,actor:Actor):Array
		{
			var mt:uint=Morton.morton(p.y/Common.tileHeight,p.x/Common.tileWidth);
			var scen:Scene=GameState.inst.scene;

			var stat:Leaf=scen.tree.getLeaf(Actor2D(actor).morton);
			var tar:Leaf=scen.tree.getLeaf(mt);
			Pathfinder.stage=scen.characterLayout;
//			Pathfinder.stage.graphics.clear();
			var traFun:Function=Pathfinder.traversableFunction;
			var path:Array=Pathfinder.findPath(stat,tar,scen.tree,traFun,actor.asType);
//			if(path)
//				Pathfinder.drawPath(path,GameState.inst.scene.characterLayout);
			return path;
		
//				Net.instance.pushRecive(MsgType.CLIENT_MOVE_IN_PATH,actor,path);
//			}
		}

	}
}